package com.changanw.tienchin.clue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.changanw.tienchin.assignment.domain.Assignment;
import com.changanw.tienchin.assignment.service.IAssignmentService;
import com.changanw.tienchin.business.domain.Business;
import com.changanw.tienchin.business.service.IBusinessService;

import com.changanw.tienchin.clue.domain.Clue;
import com.changanw.tienchin.clue.domain.vo.ClueDetails;
import com.changanw.tienchin.clue.domain.vo.ClueSummary;
import com.changanw.tienchin.clue.domain.vo.ClueVO;
import com.changanw.tienchin.clue.mapper.ClueMapper;

import com.changanw.tienchin.clue.service.IClueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changanw.tienchin.common.constant.TienChinConstants;
import com.changanw.tienchin.common.core.domain.AjaxResult;
import com.changanw.tienchin.common.core.domain.model.EchartsPoint;
import com.changanw.tienchin.common.core.domain.model.LineChartData;
import com.changanw.tienchin.common.utils.SecurityUtils;
import com.changanw.tienchin.follow.domain.FollowRecord;
import com.changanw.tienchin.follow.service.IFollowRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  线索管理服务实现类
 * </p>
 *
 * @author changanw
 * @since 2023-11-25
 */
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements IClueService {
  @Autowired
  IAssignmentService assignmentService;
  @Autowired
  ClueMapper clueMapper;
  @Autowired
  IFollowRecordService recordService;
  @Autowired
  IBusinessService businessService;

  @Override
  public List<ClueSummary> selectClueList(ClueVO clueVO) {
    return clueMapper.selectClueList(clueVO);
  }

  @Override
  public AjaxResult getClueDetailsById(Integer clueId) {

    return AjaxResult.success(clueMapper.getClueDetailsByClueId(clueId));
  }

  @Override
  @Transactional
  public AjaxResult clueFollow(ClueDetails clueDetails) {
    //更新clue表
    Clue clue = new Clue();
    BeanUtils.copyProperties(clueDetails,clue);
    clue.setStatus(TienChinConstants.CLUE_FOLLOWING);
    updateById(clue);
    //插入 tienchin_follow 表
    FollowRecord record = new FollowRecord();
    record.setAssign(clueDetails.getClueId());
    record.setCreateBy(SecurityUtils.getUsername());
    record.setCreateTime(LocalDateTime.now());
    record.setType(TienChinConstants.CLUE_TYPE);
    record.setInfo(clueDetails.getRecord());
    recordService.save(record);
    return AjaxResult.success("跟进成功");

  }

  @Override
  @Transactional
  public AjaxResult invalidClue(ClueDetails clueDetails) {

    //判断下当前次数是否大于3了，如果大于3 设置为无效线索
    Clue clue = getById(clueDetails.getClueId());
    if (clue.getFailCount() == 3){
      //无效线索次数已经极限
      UpdateWrapper<Clue> updateWrapper = new UpdateWrapper<>();
      updateWrapper.lambda().set(Clue::getStatus,TienChinConstants.CLUE_INVALIDATE).eq(Clue::getClueId,clueDetails.getClueId());
      update(updateWrapper);
      return AjaxResult.success("无效线索次数已经极限");
    }
    //1.将clue表中的fail_count 字段加1
    UpdateWrapper<Clue> uw = new UpdateWrapper<>();
    uw.lambda().setSql("fail_count = fail_count+1").eq(Clue::getClueId,clueDetails.getClueId());
    update(uw);
    //2.往根据记录中加一条数据 tienchin_follow
    FollowRecord record = new FollowRecord();
    record.setAssign(clueDetails.getClueId());
    record.setCreateBy(SecurityUtils.getUsername());
    record.setCreateTime(LocalDateTime.now());
    record.setType(TienChinConstants.CLUE_TYPE);
    record.setInfo(clueDetails.getRecord());
    recordService.save(record);
    return AjaxResult.success("设置成功");

  }

  @Override
  public AjaxResult getClueSummaryById(Integer clueId) {
    Clue byId = getById(clueId);
    return AjaxResult.success(byId);
  }

  @Override
  public AjaxResult updateClue(Clue clue) {
    return updateById(clue) ? AjaxResult.success("更新成功") : AjaxResult.error("更新失败");
  }

  @Override
  public AjaxResult deleteClueByIds(Integer[] clueIds) {
    UpdateWrapper<Clue> uw = new UpdateWrapper<>();
    uw.lambda().set(Clue::getDelFlag,1).in(Clue::getClueId,clueIds);
    return update(uw) ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
  }

  @Override
  @Transactional
  public AjaxResult clue2Business(Integer clueId) {

    Clue clue = getById(clueId);
    Business business = new Business();
    BeanUtils.copyProperties(clue,business);
    business.setCreateBy(SecurityUtils.getUsername());
    business.setCreateTime(LocalDateTime.now());
    business.setEndTime(null);
    business.setFailCount(0);
    business.setNextTime(null);
    business.setRemark(null);
    business.setUpdateBy(null);
    business.setUpdateTime(null);
    business.setStatus(TienChinConstants.BUSINESS_ALLOCATED);
    business.setNextTime(LocalDateTime.now().plusHours(TienChinConstants.NEXT_FOLLOW_TIME));
    //1.删除线索
    UpdateWrapper<Clue> uw = new UpdateWrapper<>();
    uw.lambda().set(Clue::getDelFlag,1).eq(Clue::getClueId,clueId);
    update(uw);
    //2.转为商机
    businessService.save(business);
    //3.默认将商机分配给admin
    //添加默认分配人
    Assignment assignment = new Assignment();
    assignment.setAssignId(business.getBusinessId());
    assignment.setLatest(true);
    assignment.setType(TienChinConstants.BUSINESS_TYPE);
    assignment.setUserId(TienChinConstants.ADMIN_ID);
    assignment.setUserName(TienChinConstants.ADMIN_NAME);
    assignment.setDeptId(TienChinConstants.ADMIN_DEPT_ID);
    assignment.setCreateBy(SecurityUtils.getUsername());
    assignment.setCreateTime(LocalDateTime.now());
    assignmentService.save(assignment);
    return AjaxResult.success("转为商机成功");
  }

  @Override
  @Transactional
  public AjaxResult addClue(Clue clue) {
    //新增之前使用手机号先查询一下
    QueryWrapper<Clue> qw = new QueryWrapper<>();
    qw.lambda().eq(Clue::getPhone,clue.getPhone());
    Clue one = getOne(qw);
    if (one != null){
      return AjaxResult.error("手机号重复");
    }
    clue.setCreateBy(SecurityUtils.getUsername());
    clue.setCreateTime(LocalDateTime.now());
    clue.setNextTime(LocalDateTime.now().plusHours(TienChinConstants.NEXT_FOLLOW_TIME));

    //添加线索
    save(clue);
    //添加默认分配人
    Assignment assignment = new Assignment();
    assignment.setAssignId(clue.getClueId());
    assignment.setLatest(true);
    assignment.setType(TienChinConstants.CLUE_TYPE);
    assignment.setUserId(SecurityUtils.getUserId());
    assignment.setUserName(SecurityUtils.getUsername());
    assignment.setDeptId(SecurityUtils.getDeptId());
    assignment.setCreateBy(SecurityUtils.getUsername());
    assignment.setCreateTime(LocalDateTime.now());
    assignmentService.save(assignment);
    return AjaxResult.success("线索录入成功");

  }

  @Override
  public AjaxResult clueAnalysis(ClueVO clueVO) {
    //设置一个默认时间区间
    if (clueVO.getParams().get("beginTime") == null ||
            clueVO.getParams().get("endTime") == null){
      clueVO.getParams().put("beginTime",LocalDateTime.now().minusWeeks(1));
      clueVO.getParams().put("endTime",LocalDateTime.now().plusWeeks(1));
    }
    //获取增量数据
    List<EchartsPoint> increaseData = clueMapper.increaseData(clueVO);
    //获取存量数据
    List<EchartsPoint> totalData = clueMapper.totalData(clueVO);
    LineChartData lineChartData = new LineChartData();
    lineChartData.setIncrease(increaseData);
    lineChartData.setTotal(totalData);
    return AjaxResult.success(lineChartData);
  }
}
